import requests
import json
import time

from utils.http import get_request_header
from settings import TEST_TIMEOUT
from utils.log import logger
from domain import Proxy

"""
实现代理池的校验模块
检查代理IP速度 和 匿名程度; 
  1. 代理IP速度: 就是从发送请求到获取响应的时间间隔
  2. 匿名程度检查: 
    1. 对 `http://httpbin.org/get` 或 `https://httpbin.org/get` 发送请求
    2. 如果 响应的`origin` 中有','分割的两个IP就是透明代理IP
    3. 如果 响应的`headers` 中包含 `Proxy-Connection` 说明是匿名代理IP 
    4. 否则就是高匿代理IP
检查代理IP协议类型
  如果 `http://httpbin.org/get` 发送请求可以成功, 说明支持http协议
  如果 `https://httpbin.org/get` 发送请求可以成功, 说明支持https协议 
"""


def check_proxy(proxy):
    proxies = {
        'http': "http://{}:{}".format(proxy.ip, proxy.port),
        'https': "https://{}:{}".format(proxy.ip, proxy.port)
    }

    http, nick_type, speed = _check_http_proxy(proxies)
    https, https_nick_type, https_speed = _check_http_proxy(proxies, False)

    if http and https:
        proxy.protocol = 2  # https和http都支持
        proxy.nick_type = nick_type
        proxy.speed = speed
    elif http:
        proxy.protocol = 0  # http是0
        proxy.nick_type = nick_type
        proxy.speed = speed
    elif https:
        proxy.protocol = 1
        proxy.nick_type = https_nick_type
        proxy.speed = https_speed
    else:
        proxy.protocol = -1
        proxy.nick_type = -1
        proxy.speed = -1

    # logger.debug(proxy)
    return proxy


def _check_http_proxy(proxies, is_http=True):
    nick_type = -1
    speed = -1
    if is_http:
        test_url = 'http://httpbin.org/get'
    else:
        test_url = 'https://httpbin.org/get'

    try:
        start = time.time()
        response = requests.get(test_url, headers=get_request_header(), timeout=TEST_TIMEOUT, proxies=proxies)
        if response.ok:
            speed = round(time.time() - start, 2)
            content = json.loads(response.text)
            headers = content['headers']

            ip = content["origin"]

            proxy_connection = headers.get('Proxy-Connection', None)

            if ',' in ip:
                nick_type = 2  # 透明
            elif proxy_connection:
                nick_type = 1  # 匿名
            else:
                nick_type = 0  # 高匿

            return True, nick_type, speed
        else:
            return False, nick_type, speed
    except Exception as ex:
        #logger.exception(ex)
        return False, nick_type, speed


if __name__ == '__main__':
    proxy = Proxy('182.84.81.128', '9999')
    rs = check_proxy(proxy)
    print(proxy.protocol)
    print(rs)
